const express = require('express');
const { body, validationResult } = require('express-validator');
const { query, transaction } = require('../config/database');
const router = express.Router();

// 获取用户专注设置
router.get('/settings', async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 获取用户设置
    let settings = await query(
      'SELECT * FROM focus_settings WHERE user_id = ?',
      [userId]
    );
    
    // 如果没有设置，创建默认设置
    if (settings.length === 0) {
      await query(
        'INSERT INTO focus_settings (user_id, work_duration, short_break_duration, long_break_duration, long_break_interval, auto_start_breaks, auto_start_work, sound_enabled, desktop_notifications, motivation_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
        [userId, 1500, 300, 900, 4, false, false, true, true, 'none'] // 25分钟=1500秒, 5分钟=300秒, 15分钟=900秒
      );
      settings = await query(
        'SELECT * FROM focus_settings WHERE user_id = ?',
        [userId]
      );
    }
    
    // 获取用户自定义计时器
    const timers = await query(
      'SELECT * FROM user_timers WHERE user_id = ? ORDER BY is_default DESC, created_at ASC',
      [userId]
    );
    
    // 如果没有计时器，创建默认计时器
    if (timers.length === 0) {
      await query(
        'INSERT INTO user_timers (user_id, name, work_duration, break_duration, is_default) VALUES (?, ?, ?, ?, ?)',
        [userId, '经典番茄', 1500, 300, true] // 25分钟=1500秒, 5分钟=300秒
      );
      const defaultTimers = await query(
        'SELECT * FROM user_timers WHERE user_id = ? ORDER BY is_default DESC, created_at ASC',
        [userId]
      );
      settings[0].timers = defaultTimers;
    } else {
      settings[0].timers = timers;
    }
    
    // 将数字转换为布尔值
    const settingsData = settings[0];
    if (settingsData) {
      settingsData.sound_enabled = Boolean(settingsData.sound_enabled);
      settingsData.desktop_notifications = Boolean(settingsData.desktop_notifications);
      settingsData.auto_start_breaks = Boolean(settingsData.auto_start_breaks);
      settingsData.auto_start_work = Boolean(settingsData.auto_start_work);
    }
    
    res.json({
      message: '获取专注设置成功',
      settings: settingsData
    });
  } catch (error) {
    console.error('获取专注设置错误:', error);
    res.status(500).json({ message: '获取专注设置失败' });
  }
});

// 更新用户专注设置
router.put('/settings', [
  body('work_duration').optional().isInt({ min: 1, max: 120 }).withMessage('工作时长必须在1-120分钟之间'),
  body('short_break_duration').optional().isInt({ min: 1, max: 60 }).withMessage('短休息时长必须在1-60分钟之间'),
  body('long_break_duration').optional().isInt({ min: 1, max: 120 }).withMessage('长休息时长必须在1-120分钟之间'),
  body('long_break_interval').optional().isInt({ min: 1, max: 10 }).withMessage('长休息间隔必须在1-10之间'),
  body('auto_start_breaks').optional().isBoolean().withMessage('自动开始休息必须是布尔值'),
  body('auto_start_work').optional().isBoolean().withMessage('自动开始工作必须是布尔值'),
  body('sound_enabled').optional().isBoolean().withMessage('声音提醒必须是布尔值'),
  body('desktop_notifications').optional().isBoolean().withMessage('桌面通知必须是布尔值'),
  body('motivation_type').optional().isIn(['none', 'words', 'emoji', 'random']).withMessage('激励方式必须是none、words、emoji或random')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const userId = req.user.id;
    const updateData = req.body;
    
    // 构建更新SQL
    const updateFields = [];
    const updateValues = [];
    
    Object.keys(updateData).forEach(key => {
      if (updateData[key] !== undefined) {
        updateFields.push(`${key} = ?`);
        updateValues.push(updateData[key]);
      }
    });

    if (updateFields.length === 0) {
      return res.status(400).json({ message: '没有要更新的字段' });
    }

    updateValues.push(userId);
    await query(
      `UPDATE focus_settings SET ${updateFields.join(', ')}, updated_at = NOW() WHERE user_id = ?`,
      [...updateValues]
    );
    
    res.json({ message: '专注设置更新成功' });
  } catch (error) {
    console.error('更新专注设置错误:', error);
    res.status(500).json({ message: '更新专注设置失败' });
  }
});

// 获取用户自定义计时器列表
router.get('/timers', async (req, res) => {
  try {
    const userId = req.user.id;
    
    const timers = await query(
      'SELECT * FROM user_timers WHERE user_id = ? ORDER BY is_default DESC, created_at ASC',
      [userId]
    );
    
    res.json({
      message: '获取计时器列表成功',
      timers
    });
  } catch (error) {
    console.error('获取计时器列表错误:', error);
    res.status(500).json({ message: '获取计时器列表失败' });
  }
});

// 创建自定义计时器
router.post('/timers', [
  body('name').isLength({ min: 1, max: 100 }).withMessage('计时器名称长度必须在1-100个字符之间'),
  body('work_duration').isInt({ min: 1, max: 7200 }).withMessage('工作时长必须在1-7200秒之间'),
  body('break_duration').isInt({ min: 0, max: 3600 }).withMessage('休息时长必须在0-3600秒之间')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const userId = req.user.id;
    const { name, work_duration, break_duration } = req.body;
    
    // 创建计时器
    const result = await query(
      'INSERT INTO user_timers (user_id, name, work_duration, break_duration) VALUES (?, ?, ?, ?)',
      [userId, name, work_duration, break_duration]
    );
    
    res.json({
      message: '创建计时器成功',
      timerId: result.insertId
    });
  } catch (error) {
    console.error('创建计时器错误:', error);
    res.status(500).json({ message: '创建计时器失败' });
  }
});

// 更新自定义计时器
router.put('/timers/:id', [
  body('name').optional().isLength({ min: 1, max: 100 }).withMessage('计时器名称长度必须在1-100个字符之间'),
  body('work_duration').optional().isInt({ min: 1, max: 120 }).withMessage('工作时长必须在1-120分钟之间'),
  body('break_duration').optional().isInt({ min: 0, max: 60 }).withMessage('休息时长必须在0-60分钟之间')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const userId = req.user.id;
    const timerId = req.params.id;
    const { name, work_duration, break_duration } = req.body;
    
    // 检查计时器是否属于当前用户
    const timer = await query(
      'SELECT * FROM user_timers WHERE id = ? AND user_id = ?',
      [timerId, userId]
    );
    
    if (timer.length === 0) {
      return res.status(404).json({ message: '计时器不存在' });
    }
    
    // 构建更新字段
    const updateFields = [];
    const updateValues = [];
    
    if (name !== undefined) {
      updateFields.push('name = ?');
      updateValues.push(name);
    }
    if (work_duration !== undefined) {
      updateFields.push('work_duration = ?');
      updateValues.push(work_duration);
    }
    if (break_duration !== undefined) {
      updateFields.push('break_duration = ?');
      updateValues.push(break_duration);
    }
    
    if (updateFields.length === 0) {
      return res.status(400).json({ message: '没有需要更新的字段' });
    }
    
    updateFields.push('updated_at = NOW()');
    updateValues.push(timerId, userId);
    
    // 更新计时器
    await query(
      `UPDATE user_timers SET ${updateFields.join(', ')} WHERE id = ? AND user_id = ?`,
      updateValues
    );
    
    res.json({ message: '更新计时器成功' });
  } catch (error) {
    console.error('更新计时器错误:', error);
    res.status(500).json({ message: '更新计时器失败' });
  }
});

// 删除自定义计时器
router.delete('/timers/:id', async (req, res) => {
  try {
    const userId = req.user.id;
    const timerId = req.params.id;
    
    // 检查计时器是否属于当前用户且不是默认计时器
    const timer = await query(
      'SELECT * FROM user_timers WHERE id = ? AND user_id = ?',
      [timerId, userId]
    );
    
    if (timer.length === 0) {
      return res.status(404).json({ message: '计时器不存在' });
    }
    
    if (timer[0].is_default) {
      return res.status(400).json({ message: '不能删除默认计时器' });
    }
    
    // 删除计时器
    await query(
      'DELETE FROM user_timers WHERE id = ? AND user_id = ?',
      [timerId, userId]
    );
    
    res.json({ message: '删除计时器成功' });
  } catch (error) {
    console.error('删除计时器错误:', error);
    res.status(500).json({ message: '删除计时器失败' });
  }
});

// 开始专注会话
router.post('/sessions/start', [
  body('timer_id').isInt().withMessage('计时器ID必须是整数'),
  body('session_type').isIn(['pomodoro', 'break']).withMessage('会话类型必须是pomodoro或break')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ message: errors.array()[0].msg });
    }

    const userId = req.user.id;
    const { timer_id, session_type } = req.body;
    
    // 获取计时器信息
    const timer = await query(
      'SELECT * FROM user_timers WHERE id = ? AND user_id = ?',
      [timer_id, userId]
    );
    
    if (timer.length === 0) {
      return res.status(404).json({ message: '计时器不存在' });
    }
    
    const duration = session_type === 'pomodoro' ? timer[0].work_duration : timer[0].break_duration;
    
    // 创建专注会话
    const result = await query(
      'INSERT INTO focus_sessions (user_id, session_type, duration, status) VALUES (?, ?, ?, ?)',
      [userId, session_type, duration, 'active']
    );
    
    res.json({
      message: '专注会话开始成功',
      sessionId: result.insertId,
      duration: duration
    });
  } catch (error) {
    console.error('开始专注会话错误:', error);
    res.status(500).json({ message: '开始专注会话失败' });
  }
});

// 完成专注会话
router.post('/sessions/:id/complete', async (req, res) => {
  try {
    const userId = req.user.id;
    const sessionId = req.params.id;
    
    // 检查会话是否存在且属于当前用户
    const session = await query(
      'SELECT * FROM focus_sessions WHERE id = ? AND user_id = ? AND status = ?',
      [sessionId, userId, 'active']
    );
    
    if (session.length === 0) {
      return res.status(404).json({ message: '会话不存在或已完成' });
    }
    
    await transaction(async (connection) => {
      // 更新会话状态
      await connection.execute(
        'UPDATE focus_sessions SET status = ?, completed_duration = ?, end_time = NOW() WHERE id = ?',
        ['completed', session[0].duration, sessionId]
      );
      
      // 如果是工作会话，增加积分
      if (session[0].session_type === 'pomodoro') {
        // 检查今日是否已达到5次限制
        const today = new Date().toISOString().split('T')[0];
        const todayStats = await connection.execute(
          'SELECT * FROM user_statistics WHERE user_id = ? AND stat_date = ?',
          [userId, today]
        );
        
        if (todayStats[0].length === 0) {
          // 创建今日统计记录
          await connection.execute(
            'INSERT INTO user_statistics (user_id, stat_date, focus_sessions, points_earned) VALUES (?, ?, ?, ?)',
            [userId, today, 1, 10]
          );
        } else {
          // 检查是否已达到5次限制
          if (todayStats[0][0].focus_sessions < 5) {
            // 更新统计记录
            await connection.execute(
              'UPDATE user_statistics SET focus_sessions = focus_sessions + 1, points_earned = points_earned + 10 WHERE user_id = ? AND stat_date = ?',
              [userId, today]
            );
          }
        }
        
        // 更新用户总积分
        await connection.execute(
          'UPDATE users SET total_points = total_points + 10 WHERE id = ?',
          [userId]
        );
      }
    });
    
    res.json({ message: '专注会话完成成功' });
  } catch (error) {
    console.error('完成专注会话错误:', error);
    res.status(500).json({ message: '完成专注会话失败' });
  }
});

// 获取专注会话历史
router.get('/sessions', async (req, res) => {
  try {
    const userId = req.user.id;
    const { page = 1, limit = 20 } = req.query;
    const offset = (page - 1) * limit;
    
    const sessions = await query(
      'SELECT * FROM focus_sessions WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?',
      [userId, parseInt(limit), parseInt(offset)]
    );
    
    const total = await query(
      'SELECT COUNT(*) as count FROM focus_sessions WHERE user_id = ?',
      [userId]
    );
    
    res.json({
      message: '获取专注会话历史成功',
      sessions,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: total[0].count,
        pages: Math.ceil(total[0].count / limit)
      }
    });
  } catch (error) {
    console.error('获取专注会话历史错误:', error);
    res.status(500).json({ message: '获取专注会话历史失败' });
  }
});

module.exports = router;
